package com.soft.collateral.task;

import com.soft.collateral.constant.RedisImgConstant;
import com.soft.collateral.service.FileStrategyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/8/6
 */
//@EnableScheduling
@Component
@Slf4j
@RequiredArgsConstructor
public class CleanImgTask {

    private final FileStrategyService fileStrategyService;
    private final RedisTemplate<String,Object> redisTemplate;

    //基于Cron表达式编写任务
//    @Scheduled(cron = "0 0 2 * * ? ")
    public void print5(){
        log.info(LocalDateTime.now() + "------------------- 清除图片定时任务 CleanImgTask ------------------");
        //清除的垃圾图片  Redis的Set数据类型，不重复存放，diff差集
        Set<Object> set = redisTemplate.opsForSet().difference(RedisImgConstant.UPLOAD_PIC, RedisImgConstant.UPLOAD_DB_PIC);
        if(!CollectionUtils.isEmpty(set)){
            for (Object o : set) {
                String url = (String) o;
                //删除图片
                boolean flag = fileStrategyService.deleteFile(url);
                if(flag){
                    //在Redis中删除对应的垃圾图片信息
                    redisTemplate.opsForSet().remove(RedisImgConstant.UPLOAD_PIC , url);
                    log.info("已删除图片:{}" ,url);
                }
            }
        }
    }
}
